<?php

namespace app\service;

use think\Db;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/21 0021
 * Time: 11:44
 */
class BaseService
{
    private static $_instance;

    /**
     * @name service统一访问接口
     * @author xyq
     * @return static
     */
    final public static function service()
    {
        $class = get_called_class();
        if (!isset(self::$_instance[$class]) || !(self::$_instance[$class] instanceof BaseService)) {
            self::$_instance[$class] = new static();
        }
        return self::$_instance[$class];
    }

    /**
     * @name curl请求
     * @author zay
     * @Date 2020/3/28 0028 17:32
     * @param $url
     * @param bool $params
     * @param int $method
     * @param $headers
     */

    public function http_curl($url, $params = false, $method = 0, $headers, $is_json = 1)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $url, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        if ($method) {
            var_dump($headers);
            //var_dump($params);exit;
            //$params = json_encode($params);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        if ($is_json) {
            curl_setopt($curl, CURLOPT_HTTPHEADER,
                array(
                    //'Content-Type: application/json; charset=utf-8',
                    'Content-Length:' . strlen($params))

            );
        }
        $out_put = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    }

    /**
     * @name 人脸对比
     * @author zay
     * @Date 2020/4/1 0001 12:13
     * @param $url
     * @param null $data
     * @param array $header
     * @param bool $json
     * @return array|mixed
     */

    public function http($url, $data = NULL, $header = [], $json = false)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            if ($json && is_array($data)) {
                $data = json_encode($data);
            }
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            if ($json) { //发送JSON数据
                curl_setopt($curl, CURLOPT_HEADER, 0);
                curl_setopt($curl, CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type:' . $header['content-type'],
                        'Content-Length:' . strlen($data),
                        'Accept:' . $header['accept'],
                        'Date:' . $header['date'],
                        'authorization:' . $header['authorization']
                    ));
            }
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return array('errorno' => false, 'errmsg' => $errorno);
        }
        curl_close($curl);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * @name 获取网站域名
     * @author zay
     * @Date 2020/3/31 0031 17:54
     * @return mixed
     */

    public function get_domain()
    {
        return $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
    }

    /**
     * @name 图片编码
     * @author zay
     * @Date 2020/4/1 0001 13:08
     * @param $img
     * @return string
     */

    function base64EncodeImage($img)
    {    //KM++本地图片转base64 不支持远程图片
        $image_info = getimagesize($img);
        //print_r($image_info);echo '<hr>';
        //$image_data = fread(fopen($img, 'r'), filesize($img));
        $image_data = file_get_contents($img);
        //print_r($image_data);
        $base64_image = base64_encode($image_data);
        //echo '<img src="' . $base64_image . '" />';
        return $base64_image;
    }

    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }

    /**
     * @name 上级邀请奖励币每天释放
     * @param $userinfo
     * @throws \Exception
     * @throws \think\Exception
     * @return bool
     */
    public function t_release_coin($userinfo)
    {
        $today_time = strtotime(date('Y-m-d'));
        $v = DB('invite_reward_coin')->where('last_time', '<', $today_time)
            ->where('last_time<end_time')
            ->where(['from_uid' => $userinfo['id']])->find();
        //检查用户上级邀请奖励当天是否已经释放
        $today_release_info = Db('logocoin')->where(['type' => 3, 'oid' => $userinfo['id']])
            ->whereTime('time', 'today')->find();
        if (empty($v) || $today_release_info) {
            return true;
        }
        $t_userinfo = userinfobyid($v['uid']);
        if (empty($t_userinfo)) {
            return true;
        }
        DB::startTrans();
        try {
            //计算每天释放金币数
            $release_coin = number_format($v['coin'] / $v['release_zq'], 2);
            //修改账户金币数量
            $res = DB('user')->where(['id' => $v['uid']])->setInc('idc', $release_coin);
            if (!$res) {
                throw new \Exception('账户金币变更失败');
            }
            //添加金币记录
            $log_insert = [
                'uid' => $v['uid'],
                'uname' => $v['uname'],
                'type' => 3,
                'mqian' => $t_userinfo['idc'],
                'money' => $release_coin,
                'mhou' => $t_userinfo['idc'] + $release_coin,
                'note' => '邀请奖励币释放',
                'oid' => $v['from_uid'],
                'oname' => $v['from_uname'],
                'time' => time(),
            ];
            $res1 = DB('logocoin')->insert($log_insert);
            if (!$res1) {
                throw new \Exception('金币记录添加失败');
            }
            if ($v['last_time']) {
                $last_time = $v['last_time'] + 84600;
            } else {
                $last_time = strtotime(date('Y-m-d 23:59:55'));
            }
            $res = DB('invite_reward_coin')->where(['id' => $v['id']])->update(['last_time' => $last_time]);
            if (!$res) {
                throw new \Exception('邀请奖励记录时间更新失败');
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollback();
            return false;
        }
    }
}